using System;
using System.Collections.Generic;
using Reign.Core;
using WaterDemo;

using Reign.Video.OpenGL;

namespace WaterDemo_NaCl
{
	public class MainWindow : Window
	{
		RootDisposable root;
		Video video;
		Game game;
		bool loaded, loadFailed, isShown;
	
		public MainWindow ()
		: base("Test", 512, 512)
		{
			
		}
		
		protected override void shown()
		{
			base.shown();
			
			var files = new List<string>()
			{
				"Data/Shaders/GLES2_Simulate.rs",
				"Data/Shaders/GLES2_Normal.rs",
				"Data/Shaders/GLES2_Drop.rs",
				"Data/Shaders/GLES2_Present.rs",
				"Data/Images/face.bmpc"
				//"Data/Audio/"
			};
			Streams.AddPendingFiles(files);
			
			try
			{
				OS.PostMessage("VideoStart");
				root = new RootDisposable();
				video = new Video(root, this, true);
				OS.PostMessage("VideoEnd");
			}
			catch (Exception e)
			{
				dispose();
				//Close();
				return;
			}
		
			OS.PostMessage("Shown");
			isShown = true;
		}
		
		void dispose()
		{
			if (game != null)
			{
				loaded = false;
				root.Dispose();
				game.Dispose();
				game = null;
			}
		}
		
		protected override void closing()
		{
			dispose();
			base.closing();
		}

		int loadPrint, loadTic;
		protected override void render()
		{
			if (!isShown) return;
			if (!Streams.LoadPendingFiles())
			{
				if (loadPrint == 0) OS.PostMessage("Loading: " + loadTic.ToString());
				++loadPrint;
				++loadTic;
				if (loadPrint == 100) loadPrint = 0;
				return;
			}
			
			if (!loaded && !loadFailed)
			{
				try
				{
					OS.PostMessage("Load");
					game = new Game(this, video);
					loaded = true;
					OS.PostMessage("Loaded");
					return;
				}
				catch (Exception e)
				{
					loadFailed = true;
					dispose();
					OS.PostMessage("Error: " + e.Message);
				}
			}
			
			if (loaded)
			{
				game.Update();
				if (game != null) game.Render();
			}
			
			base.render();
		}
	}
}

